package com.fingard.dsp.bank.directbank.cmbc01;

import java.io.File;
import java.sql.Connection;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.io.FileHelper;
import com.fingard.net.FormSubmit;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CMBC01SyncTask extends CMBC01Base {

    private String actNum = "";
    private String dateFrom = "";
    private String dateTo = "";

    private static final String INSERTRECEIPT = "INSERT INTO RECEIPTMAPPING(URID,BANK,OWNACT,BUSDATE,RECEIPTNO,RECEIPTFILE,CREATEDON) values (?,?,?,?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT RECEIPTFILE FROM RECEIPTMAPPING WHERE BANK=? AND OWNACT=? AND BUSDATE=? AND RECEIPTNO=?;";

    public CMBC01SyncTask(String p_actNum, String p_dateFrom, String p_dateTo) {
        actNum = p_actNum;
        dateFrom = p_dateFrom;
        dateTo = p_dateTo;
    }

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    public void downloadReceipt() {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    String uploadType = SmbFileUtil.getUploadType();
                    StringBuilder logSb = new StringBuilder();
                    Connection conn = null;
                    try {
                        String ftpFilePath = "";
                        String filePath = "";
                        setSbLog(logSb);
                        conn = FGBiz.getLocalDbConn();
                        WriteBankLogLn2(String.format("针对账号：[%s]，起始日期：[%s]，结束日期:[%s]的回单下载任务已开始执行", actNum, dateFrom, dateTo));
                        String tmpRespCode = "";
                        String tmpRespInfo = "";
                        int qryCount = 0;
                        List<Map<String, String>> tmpResult = new ArrayList<Map<String, String>>();

                        int tmpAllNum = -1;//总条数
                        int tmpReadedNum = 0;//已读取数
                        int tmpEachReqLen = 50;//每次请求条数
                        int tmpStartNO = 0;//请求页码

                        while (tmpRespCode.length() == 0) {//分页查询
                            qryCount++;
                            tmpStartNO++;
                            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                            //写入通用的头部节点
                            CMBC01Header bankHeader = new CMBC01Header();
                            if ("true".equals(getBankConfig().getValueAsString("receiptQryNewFlag"))) {
                                bankHeader.trnCode = "b2eElectNoteQryNew";
                            } else {
                                bankHeader.trnCode = "b2eElectNoteQry";
                            }
                            writeCommonHeader(xmlWriter, bankHeader);
                            xmlWriter.writeStartElement("xDataBody");
                            xmlWriter.writeElementString("insId", reqHeader.transSeqID + qryCount);
                            xmlWriter.writeElementString("saAcctNo", actNum);
                            xmlWriter.writeElementString("BeginDate", Format.Date10Format.format(Format.Date8Format.parse(dateFrom)));
                            xmlWriter.writeElementString("EndDate", Format.Date10Format.format(Format.Date8Format.parse(dateTo)));
                            xmlWriter.writeElementString("PrintState", "0");
                            xmlWriter.writeElementString("MinMoney", "");
                            xmlWriter.writeElementString("MaxMoney", "");
                            xmlWriter.writeElementString("pageNo", String.valueOf(tmpStartNO));
                            xmlWriter.writeElementString("pageSize", String.valueOf(tmpEachReqLen));
                            xmlWriter.writeEndDocument();

                            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                            XmlTextReader tmpBkReader;
                            int tmpPageRdNum = 0;
                            if (tmpStrRet[0].length() == 0) {
                                StringBuilder tmpSbMsg = new StringBuilder();
                                tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                                if (tmpBkReader != null) {
                                    String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                                    String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                                    if (tmpRetCode.equals("0")) {
                                        //总记录数
                                        if (tmpAllNum == -1) {
                                            tmpAllNum = Integer.parseInt(tmpBkReader.getFirstText("/CMBC/xDataBody/Count"));
                                        }
                                        if (tmpAllNum <= 0) {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "查无回单";
                                            break;
                                        }

                                        while (tmpBkReader.read("/CMBC/xDataBody/List/Map")) {
                                            tmpPageRdNum++;
                                            tmpReadedNum++;
                                            Map<String, String> tmpMap = new HashMap<String, String>();
                                            tmpMap.put("innerNo", tmpBkReader.readedXElement.getSingleTextNotNull("innerNo"));//回单编号
                                            tmpMap.put("TrsDate", tmpBkReader.readedXElement.getSingleTextNotNull("TrsDate"));//交易日期
                                            tmpMap.put("BillName", tmpBkReader.readedXElement.getSingleTextNotNull("BillName"));//客户名称
                                            tmpMap.put("AcNo", tmpBkReader.readedXElement.getSingleTextNotNull("AcNo"));//账号
                                            tmpMap.put("Currency", tmpBkReader.readedXElement.getSingleTextNotNull("Currency"));//币种
                                            tmpMap.put("LoanFlag", tmpBkReader.readedXElement.getSingleTextNotNull("LoanFlag"));//借贷标识
                                            tmpMap.put("TrsAmount", tmpBkReader.readedXElement.getSingleTextNotNull("TrsAmount"));//交易金额
                                            tmpMap.put("PrintCount", tmpBkReader.readedXElement.getSingleTextNotNull("PrintCount"));//打印次数
                                            tmpMap.put("FileName", tmpBkReader.readedXElement.getSingleTextNotNull("FileName"));//文件名称
                                            if ("true".equals(getBankConfig().getValueAsString("receiptQryNewFlag"))) {
                                                tmpMap.put("SvrId", tmpBkReader.readedXElement.getSingleTextNotNull("svrId"));//交易流水号
                                            }
                                            tmpResult.add(tmpMap);
                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpRetMessage;
                                        break;
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = tmpSbMsg.toString();
                                    break;
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpStrRet[1];
                                break;
                            }

                            if (tmpPageRdNum == 0 || tmpReadedNum >= tmpAllNum) {
                                break;
                            }
                        }//分页查询

                        WriteBankLogLn(tmpRespInfo + "\r\n");
                        StringBuilder json = new StringBuilder();
                        if (getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                            json.append("tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[");
                        } else {
                            json.append("transType=downloadreceipt&data={\"rows\":[");
                        }

                        StringBuilder sendToAtsData = new StringBuilder();
                        int downloadSucc = 0;
                        int uploadSucc = 0;
                        for (Map<String, String> eachRecord : tmpResult) {
                            String tmpFilePath = "";
                            int uploadResult = -1;
                            Map<String, Object> tabMap = null;
                            tabMap = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{reqHeader.bankCode, actNum, Integer.parseInt(eachRecord.get("TrsDate").replace("-", "")), eachRecord.get("innerNo")});
                            if (tabMap != null && tabMap.size() > 0 && tabMap.containsKey("RECEIPTFILE")) {
                                downloadSucc++;
                                uploadSucc++;
                                tmpFilePath = tabMap.get("RECEIPTFILE").toString();
                                filePath = tmpFilePath;
                                uploadResult = 0;
                                eachRecord.put("downloadFlag", "之前已下载成功/上传成功");
                            } else {
                                qryCount++;
                                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                                //写入通用的头部节点
                                CMBC01Header bankHeader = new CMBC01Header();
                                bankHeader.trnCode = "b2eElectNoteDownLoad";
                                writeCommonHeader(xmlWriter, bankHeader);
                                xmlWriter.writeStartElement("xDataBody");
                                xmlWriter.writeElementString("insId", reqHeader.transSeqID + qryCount);
                                xmlWriter.writeElementString("innerNo", eachRecord.get("innerNo"));
                                String fileName = eachRecord.get("FileName");
                                xmlWriter.writeElementString("xmlFileName", fileName);
                                xmlWriter.writeEndDocument();

                                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                                XmlTextReader tmpBkReader;

                                if (tmpStrRet[0].length() == 0) {
                                    StringBuilder tmpSbMsg = new StringBuilder();
                                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                                    if (tmpBkReader != null) {
                                        String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                                        String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                                        if (tmpRetCode.equals("0")) {
                                            String fileContent = tmpBkReader.getFirstText("/CMBC/xDataBody/DownloadFileContent");
                                            String downloadFileName = tmpBkReader.getFirstText("/CMBC/xDataBody/DownloadFileName");
                                            String tmpByDate = Format.Date8Format.format(new Date());
                                            tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8);
                                            tmpFilePath = tmpByDate + "/" + reqHeader.bankCode + "/" + actNum + "/" + eachRecord.get("TrsDate").replace("-", "") + "/" + downloadFileName;
                                            if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                                String tmpFileFullPath = StringHelper.trimEnd(FGBiz.dspCenter.dspSet.receiptShareDir, "/") + "/" + tmpFilePath;
                                                if ("smb".equals(uploadType)) {
                                                    WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                    uploadResult = SmbFileUtil.smbWrite(tmpFileFullPath, new sun.misc.BASE64Decoder().decodeBuffer(fileContent), getSbLog());
                                                } else {
//                                                String localPath=FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + downloadFileName;

                                                    if ("localhost".equals(uploadType)) {
                                                        String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                        WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                        if (FileHelper.existFile(shareDir + tmpFilePath)) {
                                                            uploadResult = 1;
                                                            WriteBankLogLn(tmpFilePath + "文件已存在");
                                                        } else {
                                                            FileHelper.writeBytesToFile(shareDir + tmpFilePath, new sun.misc.BASE64Decoder().decodeBuffer(fileContent));
                                                            if (FileHelper.existFile(shareDir + tmpFilePath)) {
                                                                uploadResult = 0;
                                                            } else {
                                                                uploadResult = -1;
                                                                WriteBankLogLn(tmpFilePath + "文件上传失败");
                                                            }
                                                        }
                                                    } else {
                                                        //String localPath=FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + downloadFileName;
                                                        if (!FileHelper.existFile(tmpFileFullPath)) {
                                                            FileHelper.writeBytesToFile(tmpFileFullPath, new sun.misc.BASE64Decoder().decodeBuffer(fileContent));
                                                        }
                                                        tmpByDate = tmpByDate + "/" + actNum;
                                                        WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                        Map<String, String> map = FormSubmit.fileUpload
                                                                (FGBiz.dspCenter.dspSet.receiptShareDir, actNum, tmpFileFullPath, tmpByDate, downloadFileName, getCharset());
                                                        WriteBankLogStep3(JSON.toJSONString(map));
                                                        if (map.keySet().size() != 0) {
                                                            uploadResult = Integer.valueOf(map.get("respCode"));
                                                            tmpFilePath = map.get("remotePath");
                                                        } else {
                                                            uploadResult = -1;
                                                        }
                                                    }
                                                }
                                            } else {
                                                //创建临时文件夹
                                                String localPath = FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + downloadFileName;
                                                if (!FileHelper.existFile(localPath)) {
                                                    FileHelper.writeBytesToFile(localPath, new sun.misc.BASE64Decoder().decodeBuffer(fileContent));
                                                }
                                                //ftp服务器
                                                FtpSet ftpSet2 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet2.upDir);
                                                //上传ftp服务器的地址
                                                String newFilePath = Format.Date8Format.format(new Date());
                                                newFilePath = newFilePath.substring(0, 6) + "/" + newFilePath.substring(6, 8) + "/" + reqHeader.bankCode + "/" + actNum + "/";
                                                filePath = newFilePath + downloadFileName;
                                                ftpFilePath = StringHelper.trimEndFileSp(ftpSet2.upDir) + "/" + filePath;
                                                WriteBankLogLn("开始将回单" + localPath + "上传至" + ftpFilePath);
                                                //上传至ftp
                                                uploadResult = FtpUtil.ftpUploading(ftpSet2, localPath, ftpFilePath);
                                                tmpFilePath = ftpFilePath;
                                                if (uploadResult > -1) {
                                                    FileHelper.deleteFileIfExists(localPath);
                                                }
                                            }
                                            downloadSucc++;
                                            if (uploadResult < 0) {
                                                eachRecord.put("downloadFlag", "下载成功/上传失败");
                                            } else {
                                                uploadSucc++;
                                                eachRecord.put("downloadFlag", "下载成功/上传成功");
                                                JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{UUID.randomUUID().toString(), reqHeader.bankCode, actNum, eachRecord.get("TrsDate").replace("-", ""), eachRecord.get("innerNo"), tmpFilePath, new Date()});
                                            }
                                        } else {
                                            WriteBankLogLn(fileName + "下载失败：" + tmpRetMessage + "\r\n");
                                            eachRecord.put("downloadFlag", tmpRetMessage);
                                        }
                                    } else {
                                        WriteBankLogLn(fileName + "下载失败：" + tmpSbMsg.toString() + "\r\n");
                                        eachRecord.put("downloadFlag", tmpSbMsg.toString());
                                    }
                                } else {
                                    WriteBankLogLn(fileName + "下载失败：" + tmpStrRet[1] + "\r\n");
                                    eachRecord.put("downloadFlag", tmpStrRet[1]);
                                }
                            }

                            if (uploadResult >= 0 && StringHelper.hasAnyChar(tmpFilePath)) {//推送数据给ATS处理
                                sendToAtsData.append("{");
                                sendToAtsData.append("\"actNum\":\"" + actNum + "\",");
                                sendToAtsData.append("\"actCur\":\"" + convertCurToATS(eachRecord.get("Currency")) + "\",");
                                sendToAtsData.append("\"receiptCode\":\"" + eachRecord.get("innerNo") + "\",");//回单编号
                                sendToAtsData.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                sendToAtsData.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                sendToAtsData.append("\"oppActName\":\"" + "" + "\",");
                                sendToAtsData.append("\"oppActNum\":\"" + "" + "\",");
                                sendToAtsData.append("\"amount\":\"" + eachRecord.get("TrsAmount") + "\",");
                                sendToAtsData.append("\"moneyway\":\"" + ("0".equals(eachRecord.get("LoanFlag")) ? "1" : "2") + "\",");
                                if ("true".equals(getBankConfig().getValueAsString("receiptQryNewFlag"))) {
                                    sendToAtsData.append("\"tranSeqNo\":\"" + eachRecord.get("SvrId") + "\",");
                                } else {
                                    sendToAtsData.append("\"tranSeqNo\":\"" + eachRecord.get("innerNo") + "\",");
                                }
                                sendToAtsData.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                sendToAtsData.append("\"tranDate\":\"" + eachRecord.get("TrsDate") + "\",");
                                if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                    if ("smb".equals(uploadType)) {
                                        sendToAtsData.append("\"filePath\":\"" + tmpFilePath + "\",");//回单文件仓库存储路径
                                    } else {
                                        sendToAtsData.append("\"filePath\":\"" + tmpFilePath + "\",");//文件路径
                                    }
                                } else {
                                    sendToAtsData.append("\"filePath\":\"" + filePath + "\",");//文件路径
                                }
                                sendToAtsData.append("\"fileType\":\"1\"");
                                sendToAtsData.append("},");
                            }
                        }
                        if (sendToAtsData.toString().length() > 0) {
                            sendToAtsData.deleteCharAt(sendToAtsData.length() - 1);
                            sendToAtsData.append("]}");

                            String sendToAtsStr = json.toString() + sendToAtsData.toString();

                            String[] data;
                            String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                            //宁波银行专用
                            if ("nbGateway".equals(receiptPushType)) {
                                WriteBankLogLn("3.推送给网关的数据" + sendToAtsStr.toString());
                                DirectBase tmplogMsg = new DirectBase();
                                data = FormSubmit.receiptInfoSend(sendToAtsStr.toString(), tmplogMsg, false);
                                WriteBankLogLn(tmplogMsg.getSbLog());
                                if (data[0].length() == 0 && data[1].equals("ok")) {
                                    WriteBankLogLn("推送数据到网关成功,请查看数据");
                                } else {
                                    WriteBankLogLn("推送数据到网关失败");
                                }
                            } else {
                                WriteBankLogLn("3.推送给ATS的数据" + sendToAtsStr.toString());
                                data = sendToATS(sendToAtsStr.toString());
                                if (data[0].length() == 0 && data[1].equals("ok")) {
                                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                                } else {
                                    WriteBankLogLn("推送数据到ATS失败");
                                }
                            }

                        } else {
                            WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
                        }
                        for (Map<String, String> eachRecord : tmpResult) {
                            WriteBankLogLn(String.format("回单编号：[%s]所对应的处理结果：[%s]", eachRecord.get("innerNo"), eachRecord.get("downloadFlag")));
                        }
                        WriteBankLogLn(String.format("总计：[%s]回单，下载成功：[%s]，上传成功:[%s]的回单下载任务已完成执行", tmpResult.size(), downloadSucc, uploadSucc));
                        WriteBankLogLn(String.format("针对账号：[%s]，起始日期：[%s]，结束日期:[%s]的回单下载任务已完成执行", actNum, dateFrom, dateTo));

                    } catch (Exception ex) {
                        WriteBankLogLn(ex);
                        ex.printStackTrace();
                    } finally {
                        String tmpDateDir = Format.DateForLogFormat.format(new Date()).replace("-", File.separator);
                        String tmpSubFileName = FGBiz.dspCenter.bankLogsFirstDir + File.separator + tmpDateDir + File.separator + "CMBC01" + File.separator + "SyncTask-downloadReceipt" + "_" + actNum + "_" + Format.DateTime14Format.format(new Date()) + "_" + UUID.randomUUID() + ".txt";
                        String tmpLogFile = FGBiz.dspCenter.bankLogsDirPath + File.separator + tmpSubFileName;
                        try {
                            FileHelper.writeFile(tmpLogFile, logSb);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                        if (conn != null) {
                            try {
                                conn.close();
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            });
    }
}
